package com.hepinghospital.user.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.base.BaseFragment;
import com.hepinghospital.user.eventbus.VersionUpdateEvent;
import com.hepinghospital.user.ui.activity.nursing.MyNursingOrderActivity;
import com.hepinghospital.user.ui.activity.prescription.MyMedicineActivity;
import com.hepinghospital.user.ui.activity.userinfo.MyAskActivity;
import com.hepinghospital.user.ui.activity.userinfo.MyFamilyActivity;
import com.hepinghospital.user.ui.activity.userinfo.SettingActivity;
import com.hepinghospital.user.ui.activity.userinfo.UserInfoActivity;
import com.hepinghospital.user.ui.dialog.GuideDialog;
import com.hepinghospital.user.ui.dialog.UpdateDialog;
import com.hepinghospital.user.ui.kotlin.DailyRecordListActivity;
import com.hepinghospital.user.util.DataUtil;
import com.hepinghospital.user.util.HarmonyUtil;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.PermissionsChecker;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.VersionResponse;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import butterknife.BindView;
import butterknife.OnClick;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UtilString;

/**
 * 个人中心
 * Created by Administrator on 2018/5/25.
 */

public class MineFragment1 extends BaseFragment {
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_account)
    TextView tvAccount;
    @BindView(R.id.img_head)
    ImageView img_head;
    @BindView(R.id.tv_family)
    TextView tvFamily;
    @BindView(R.id.my_order)
    TextView myOrder;
    @BindView(R.id.tv_graphic_consultation)
    TextView tvGraphicConsultation;
    @BindView(R.id.tv_cloud_clinic)
    TextView tvCloudClinic;
    @BindView(R.id.tv_my_medicine)
    TextView tvMyMedicine;
    @BindView(R.id.tv_consultation_record)
    TextView tvConsultationRecord;
    @BindView(R.id.tv_help_center)
    TextView tvHelpCenter;
    @BindView(R.id.tv_update_version)
    TextView tvUpdateVersion;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.dot)
    View dot;
    @BindView(R.id.fl_phone)
    FrameLayout flPhone;

    private UpdateDialog mUpdateDialog;

    private GuideDialog guideDialog;

    private PermissionsChecker mPermissionsChecker;

    @SuppressLint("StaticFieldLeak")
    private static MineFragment1 mineFragment;

    public static MineFragment1 newInstance() {
        if (mineFragment == null) {
            mineFragment = new MineFragment1();
        }
        return mineFragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_mine1;
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void initData() {
    }


    @Override
    public void onResume() {
        super.onResume();
        if (!UtilString.isEmpty(BaseApplication.name)) {
            tv_name.setText(BaseApplication.name);
        }
        if (!UtilString.isEmpty(BaseApplication.xyAccount)) {
            tvAccount.setText(DataUtil.INSTANCE.hidePhoneNo(BaseApplication.xyAccount));
        }
        if (!UtilString.isEmpty(BaseApplication.avatar)) {
            ImageLoaderHelper.getInstance().setCirclePicture(mContext, img_head, BaseApplication.avatar);
        } else {
            if ("女".equals(BaseApplication.sex)) {
                img_head.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_head_user_woman));
            } else {
                img_head.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_head_user_man));
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onVersionUpdate(VersionUpdateEvent updateEvent) {
        if (updateEvent.isUpdate) {
            dot.setVisibility(View.VISIBLE);
            tvUpdateVersion.setText("请下载最新版本");
        } else {
            dot.setVisibility(View.GONE);
            tvUpdateVersion.setText("检查更新");
        }
        tvVersion.setText(updateEvent.currentVersion);
    }

    @SuppressLint("SetTextI18n")
    private void setNum(TextView tv, int num) {
        if (num == 0) {
            tv.setVisibility(View.INVISIBLE);
        } else {
            tv.setVisibility(View.VISIBLE);
            tv.setText(num + "");
        }
    }

    @OnClick({R.id.ll_top, R.id.tv_graphic_consultation, R.id.tv_cloud_clinic, R.id.tv_my_nursing, R.id.tv_my_medicine,
            R.id.tv_daily_record, R.id.tv_consultation_record, R.id.tv_family, R.id.tv_help_center, R.id.tv_update_version, R.id.fl_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_top:
                startActivity(new Intent(mContext, UserInfoActivity.class));
                break;
            case R.id.tv_graphic_consultation: {
                Bundle bundle = new Bundle();
                bundle.putInt("page", 0);
                bundle.putInt("type", 1);
                startActivity(MyAskActivity.class, bundle);
                break;
            }

            case R.id.tv_cloud_clinic:
                Bundle bundle1 = new Bundle();
                bundle1.putInt("page", 0);
                bundle1.putInt("type", 0);
                startActivity(MyAskActivity.class, bundle1);
                break;
            case R.id.tv_my_nursing:
//                startActivity(new Intent(mContext, MyNursingOrderActivity.class));
                startActivity(new Intent(mContext, MyNursingOrderActivity.class));
//                startActivity( new Intent( mContext, AppointNurseListActivity.class ) );
                break;
            case R.id.tv_my_medicine:
            case R.id.tv_consultation_record:
                startActivity(new Intent(mContext, MyMedicineActivity.class));
                break;
            case R.id.tv_daily_record:
                startActivity(DailyRecordListActivity.class);
                break;
            case R.id.tv_family:
                //家族成员
                Bundle bundleFamily = new Bundle();
                bundleFamily.putInt(UIConstants.INTO_MyFamilyActivity_FLAG, UIConstants.INTO_MyFamilyActivity_FLAG_1);
                startActivity(MyFamilyActivity.class, bundleFamily);
                break;
            case R.id.tv_help_center:
                //帮助中心
                startActivity(SettingActivity.class);
                break;
            case R.id.tv_update_version:
                getVersion();
                break;
            case R.id.fl_phone:
                checkPermission();
                break;
            default:
                break;
        }
    }

    @SuppressLint("CheckResult")
    public void checkPermission() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.CALL_PHONE)
                .subscribe(granted -> {
                    if (granted) {
                        call();
                    } else {
                        ToastUtil.showToast(mContext, "请授予拨打电话的权限,否者无法使用");
                    }
                });
    }

    private void call() {
        // 拨打电话
        try {
            // 创建意图
            Intent intent = new Intent(Intent.ACTION_CALL);
            // 设置拨打电话的号码
            intent.setData(android.net.Uri.parse("tel:566-99999"));
            // 开始拨打电话
            startActivity(intent);
        } catch (Exception e) {
            LogUtil.e("info", "call: 拨打电话失败");
        }
    }


    private void showPureModeDialog() {
        guideDialog = GuideDialog.newInstance();
        guideDialog.setmListener(new GuideDialog.OnItemClickListener() {
            @Override
            public void onConfirm() {
                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }

            @Override
            public void onCancel() {

            }
        });
        guideDialog.show(getChildFragmentManager(), "guideDialog");
    }

    private void getVersion() {
        RestProxy.getInstance().getVersion(new BaseObserver<VersionResponse>() {
            @Override
            public void onSuccess(VersionResponse versionResponse) {
                PackageManager pm = mContext.getPackageManager();
                PackageInfo pi;
                String versionName = "";
                int versionCode = 0;
                try {
                    pi = pm.getPackageInfo(mContext.getPackageName(), 0);
                    versionCode = pi.versionCode;
                    versionName = pi.versionName;
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                if (versionResponse.vision > versionCode) {
                    if (HarmonyUtil.readPureModeState(mContext) == 1) {
                        showCodeDialog(versionResponse.url, versionResponse.isUpdate);
                    } else {
                        showPureModeDialog();
                    }
                } else {
                    ToastUtil.showToast(mContext, "已经是最新版本了！");
                }
                EventBus.getDefault().postSticky(new VersionUpdateEvent(versionResponse.url, versionName, versionResponse.vision > versionCode));
            }
        });
    }

    private void showCodeDialog(String url, int isUpdate) {

        mUpdateDialog = UpdateDialog.newInstance(isUpdate, false);
        mUpdateDialog.show(getChildFragmentManager(), "mUpdateDialog");
        mUpdateDialog.setmListener(new UpdateDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                Intent intent = new Intent();
                intent.setData(Uri.parse(url));//Url 就是你要打开的网址
                intent.setAction(Intent.ACTION_VIEW);
                startActivity(intent); //启动浏览器
                requireActivity().finish();
            }

            @Override
            public void onCancel() {

            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public static boolean checkAliPayInstalled(Context context) {

        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }

    /**
     * 支付宝小程序
     *
     * @param context 上下文处理
     * @param appId   小程序appId
     * @param page    小程序跳转的页面。如果不设置，默认为跳转至首页。例如：pages/user/user
     * @param query   启动参数，内容按照格式为参数名=参数值&参数名=参数值…之后encode，例如：client_type=2
     */
    public static void start(Context context, String appId, String page, String query) {
        try {
            StringBuilder sb = new StringBuilder("alipays://platformapi/startapp?");
            sb.append("appId=").append(appId).append("&");
            sb.append("page=").append(page).append("&");
            String link = URLEncoder.encode(query, "UTF-8");
            sb.append("query=").append(link);
            Uri uri = Uri.parse(sb.toString());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(intent);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
